package org.bai.miaoshaproject.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.bai.miaoshaproject.dao.PromoDOMapper;
import org.bai.miaoshaproject.dataobject.PromoDO;
import org.bai.miaoshaproject.service.PromoService;
import org.bai.miaoshaproject.service.model.PromoModel;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * ClassName PromoServiceImpl
 *
 * @author Bai
 * @version 1.0
 * @date 2019/6/2 0002 下午 16:14
 **/

@Slf4j
@Service
public class PromoServiceImpl implements PromoService {

    private final PromoDOMapper promoDOMapper;

    @Autowired
    public PromoServiceImpl(PromoDOMapper promoDOMapper) {
        this.promoDOMapper = promoDOMapper;
    }

    @Override
    public PromoModel getPromoByItemId(Integer itemId) {

        // 获取对应的商品的秒杀活动
        PromoDO promoDO = promoDOMapper.selectByItemId(itemId);

        // dataObject -> model
        PromoModel promoModel = this.convertFromDataObject(promoDO);
        if(promoModel == null){
            return null;
        }

        // 判断当前时间是否为秒杀活动
        DateTime now = new DateTime();
        if(promoModel.getStartDate().isAfterNow()){
            promoModel.setStatus(1);
        } else if(promoModel.getEndDate().isBeforeNow()){
            promoModel.setStatus(3);
        } else {
            promoModel.setStatus(2);
        }

        return promoModel;
    }

    private PromoModel convertFromDataObject(PromoDO promoDO){
        if(promoDO == null){
            return null;
        }
        PromoModel promoModel = new PromoModel();
        BeanUtils.copyProperties(promoDO, promoModel);
        promoModel.setStartDate(new DateTime(promoDO.getStartDate()));
        promoModel.setEndDate(new DateTime(promoDO.getEndDate()));
        return promoModel;
    }
}
